﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class MouseEvent : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
{
    public RawImage rawImage;
    RectTransform rectTf;

    // Start is called before the first frame update
    void Start()
    {
        rawImage = GetComponent<RawImage>();
        rectTf = GetComponent<RectTransform>();
    }


    public void OnPointerDown(PointerEventData eventData)
    {
        //Vector3 worldPos = Camera.main.ScreenToWorldPoint(eventData.position);
        //Vector3 localPos = rawImage.gameObject.transform.InverseTransformPoint(worldPos);
        //print(localPos);
        Vector2 localPoint;

        //将屏幕空间的点转换成RectTransform指定的本地空间点
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTf, eventData.position, eventData.pressEventCamera, out localPoint))
        {

            //// localPoint 是相对于轴点的本地坐标，和轴点有关
            //Debug.Log("Clicked position (local): " + localPoint);

            //转换成归一化的坐标，范围是0到1，和轴点无关，ugui左下角为(0, 0)，右上角为(1, 1)
            Vector2 normalizedPoint = Rect.PointToNormalized(rectTf.rect, localPoint);
            //Debug.Log("Clicked position (normalized): " + normalizedPoint);
            //GameStart.Ins.MouseOnClickEvent(normalizedPoint, false);
            GameStart.Ins.AddEvent(false,normalizedPoint, false);
            //relativePos是轴点为(0.5,0.5)时的本地坐标
            //Vector2 pivot = rectTf.pivot;
            //Vector2 size = new Vector2(rectTf.rect.width, rectTf.rect.height);
            //Vector2 offsetPivot = new Vector2(0.5f, 0.5f) - pivot;
            //Vector2 relativePos = localPoint - offsetPivot * size;
            //Debug.Log("Clicked position relative to pivot(0.5f,0.5f)(local):" + relativePos);

        }
    }

    public void OnDrag(PointerEventData eventData)
    {
       
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        Vector2 localPoint;
        if (RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTf, eventData.position, eventData.pressEventCamera, out localPoint))
        {
            Vector2 normalizedPoint = Rect.PointToNormalized(rectTf.rect, localPoint);
            //GameStart.Ins.MouseOnClickEvent(normalizedPoint, true);
            GameStart.Ins.AddEvent(false, normalizedPoint, true);
        }
    }
}
